#!/usr/bin/env python3
"""
资产收集Agent打包脚本 - 终极兼容版本
支持: Win7/8/10/11/2008/2012/2016/2019/2022
"""

import os
import sys
import shutil
import platform
import subprocess
from pathlib import Path


def check_and_install_dependencies():
    """检查和安装必要的依赖"""
    required_packages = {
        'pyinstaller': 'pyinstaller',
        'pillow': 'pillow',
        'pystray': 'pystray',
        'psutil': 'psutil',
        'requests': 'requests'
    }

    missing_packages = []
    for package, install_name in required_packages.items():
        try:
            if package == 'pillow':
                import PIL
            else:
                __import__(package)
            print(f"✅ {package} 已安装")
        except ImportError:
            print(f"❌ {package} 未安装")
            missing_packages.append(install_name)

    if missing_packages:
        print(f"\n正在安装缺失的包: {missing_packages}")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install"] + missing_packages)
            print("✅ 所有依赖安装完成")
        except subprocess.CalledProcessError:
            print("❌ 依赖安装失败，请手动安装")
            return False
    return True


def create_icon():
    """创建应用程序图标"""
    try:
        from PIL import Image, ImageDraw, ImageFont
    except ImportError:
        print("Pillow不可用，跳过图标创建")
        return None

    icon_path = "icon.ico"
    if os.path.exists(icon_path):
        return icon_path

    print("创建应用程序图标...")
    try:
        # 创建64x64图标
        image = Image.new('RGBA', (64, 64), (0, 0, 0, 0))
        dc = ImageDraw.Draw(image)

        # 绘制渐变背景
        for i in range(64):
            color = (30, 144, 255, int(255 * (i / 64)))
            dc.line([(0, i), (64, i)], fill=color)

        # 绘制中心圆圈
        dc.ellipse([16, 16, 48, 48], fill=(255, 255, 255, 200), outline=(255, 255, 255))

        # 添加文字
        try:
            font = ImageFont.truetype("arial.ttf", 20)
        except:
            font = ImageFont.load_default()

        dc.text((32, 32), "A", fill=(30, 144, 255), font=font, anchor="mm")
        image.save(icon_path, format='ICO')
        print(f"✅ 图标已创建: {icon_path}")
        return icon_path
    except Exception as e:
        print(f"❌ 图标创建失败: {e}")
        return None


def create_version_info():
    """创建版本信息文件"""
    version_content = '''# UTF-8
VSVersionInfo(
  ffi=FixedFileInfo(
    filevers=(2, 0, 0, 0),
    prodvers=(2, 0, 0, 0),
    mask=0x3f,
    flags=0x0,
    OS=0x40004,
    fileType=0x1,
    subtype=0x0,
    date=(0, 0)
  ),
  kids=[
    StringFileInfo(
      [
        StringTable(
          u'040904B0',
          [StringStruct(u'CompanyName', u'AssetAgent'),
           StringStruct(u'FileDescription', u'Asset Collection Agent'),
           StringStruct(u'FileVersion', u'2.0.0.0'),
           StringStruct(u'InternalName', u'AssetAgent'),
           StringStruct(u'LegalCopyright', u'Copyright 2024'),
           StringStruct(u'OriginalFilename', u'AssetAgent.exe'),
           StringStruct(u'ProductName', u'Asset Collection Agent'),
           StringStruct(u'ProductVersion', u'2.0.0.0')])
      ]),
    VarFileInfo([VarStruct(u'Translation', [0x409, 1200])])
  ]
)
'''
    with open('version_info.txt', 'w', encoding='utf-8') as f:
        f.write(version_content)
    print("✅ 版本信息文件已创建")
    return 'version_info.txt'


def build_agent():
    """构建Agent主函数"""
    print("\n" + "=" * 60)
    print("开始构建资产收集Agent - 多系统兼容版本")
    print("=" * 60)

    # 创建图标
    icon_path = create_icon()

    # 创建版本信息
    version_file = create_version_info()

    # PyInstaller配置
    pyinstaller_args = [
        'agent.py',
        '--name=AssetAgent',
        '--onefile',
        '--noconsole',  # 无控制台窗口
        '--clean',
        '--noconfirm',
    ]

    # 添加图标
    if icon_path and os.path.exists(icon_path):
        pyinstaller_args.append(f'--icon={icon_path}')

    # 添加版本信息
    if os.path.exists(version_file):
        pyinstaller_args.append(f'--version-file={version_file}')

    # 隐藏导入 - 核心模块
    hidden_imports = [
        'requests', 'psutil', 'pystray', 'PIL', 'PIL.Image', 'PIL.ImageDraw', 'PIL.ImageFont',
        'tkinter', 'tkinter.ttk', 'winreg', 'ctypes', 'subprocess', 'json', 'logging',
        'threading', 'datetime', 'platform', 'socket', 'argparse', 'tempfile', 'os', 'sys',
        'pathlib', 'queue', 'urllib3', 'chardet', 'idna', 'certifi', 'encodings',
        'encodings.utf_8', 'encodings.ascii', 'encodings.idna',
        # Windows特定
        'pystray._win32', 'psutil._psutil_windows',
        # PIL相关
        'PIL._imaging', 'PIL._imagingft', 'PIL._imagingtk'
    ]

    for imp in hidden_imports:
        pyinstaller_args.append(f'--hidden-import={imp}')

    # 排除不必要的模块以减少体积
    pyinstaller_args.extend([
        '--exclude-module=test',
        '--exclude-module=tests',
        '--exclude-module=tkinter.test',
    ])

    print(f"PyInstaller 参数数量: {len(pyinstaller_args)}")
    print("开始打包过程...")

    try:
        import PyInstaller.__main__
        PyInstaller.__main__.run(pyinstaller_args)

        # 检查生成的文件
        exe_path = 'dist/AssetAgent.exe'
        if os.path.exists(exe_path):
            file_size = os.path.getsize(exe_path) / (1024 * 1024)
            print(f"\n✅ 打包成功!")
            print(f"📁 生成文件: {exe_path}")
            print(f"📊 文件大小: {file_size:.2f} MB")

            # 兼容性信息
            print("\n🏆 兼容性信息:")
            print("  ✅ Windows 7 SP1 及以上")
            print("  ✅ Windows 8/8.1")
            print("  ✅ Windows 10/11")
            print("  ✅ Windows Server 2008 R2 及以上")
            print("  ✅ 无控制台黑框")
            print("  ✅ 系统托盘运行")

            # 使用说明
            print("\n📖 使用说明:")
            print("  1. 双击 AssetAgent.exe 打开配置界面")
            print("  2. 使用 AssetAgent.exe --minimized 直接后台运行")
            print("  3. 右键托盘图标进行各种操作")

            return True
        else:
            print("❌ 错误: 可执行文件未生成")
            return False

    except Exception as e:
        print(f"❌ 打包失败: {e}")
        import traceback
        traceback.print_exc()
        return False


def cleanup_temp_files():
    """清理临时文件"""
    temp_files = ['build', 'AssetAgent.spec', 'version_info.txt']
    cleaned = []

    for item in temp_files:
        if os.path.exists(item):
            try:
                if os.path.isdir(item):
                    shutil.rmtree(item)
                else:
                    os.remove(item)
                cleaned.append(item)
            except Exception as e:
                print(f"⚠️  清理 {item} 失败: {e}")

    if cleaned:
        print(f"✅ 已清理临时文件: {', '.join(cleaned)}")


def main():
    """主函数"""
    print("资产收集Agent - 终极兼容打包工具")
    print("=" * 60)

    # 环境信息
    print(f"🐍 Python版本: {platform.python_version()}")
    print(f"💻 系统架构: {platform.architecture()[0]}")
    print(f"🖥️  操作系统: {platform.system()} {platform.release()}")

    # 检查依赖
    if not check_and_install_dependencies():
        print("❌ 依赖检查失败，请手动安装所需包")
        return

    # 构建
    if build_agent():
        # 询问是否清理
        cleanup = input("\n是否清理临时构建文件? (y/N): ").lower().strip()
        if cleanup in ['y', 'yes']:
            cleanup_temp_files()
        else:
            print("ℹ️  保留临时文件以便调试")
    else:
        print("\n❌ 构建失败，请检查错误信息")
        sys.exit(1)


if __name__ == '__main__':
    main()